package com.zenithmind.mall.pojo.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.zenithmind.common.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 百亿补贴订单实体 - 遵循单一职责原则，专门管理补贴订单信息
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("mall_subsidy_order")
public class SubsidyOrder extends BaseEntity {

    /**
     * 关联的订单ID
     */
    private String orderId;

    /**
     * 用户ID
     */
    private String userId;

    /**
     * 补贴活动ID
     */
    private String activityId;

    /**
     * 补贴商品ID
     */
    private String subsidyProductId;

    /**
     * 商品ID
     */
    private String productId;

    /**
     * 购买数量
     */
    private Integer quantity;

    /**
     * 原价
     */
    private BigDecimal originalPrice;

    /**
     * 补贴后价格
     */
    private BigDecimal subsidyPrice;

    /**
     * 单品补贴金额
     */
    private BigDecimal unitSubsidyAmount;

    /**
     * 总补贴金额
     */
    private BigDecimal totalSubsidyAmount;

    /**
     * 订单原总金额
     */
    private BigDecimal originalTotalAmount;

    /**
     * 订单补贴后总金额
     */
    private BigDecimal subsidyTotalAmount;

    /**
     * 补贴状态（0-待生效，1-已生效，2-已取消，3-已退款）
     */
    private Integer subsidyStatus;

    /**
     * 补贴生效时间
     */
    private LocalDateTime subsidyEffectiveTime;

    /**
     * 补贴取消时间
     */
    private LocalDateTime subsidyCancelTime;

    /**
     * 补贴取消原因
     */
    private String subsidyCancelReason;

    /**
     * 补贴退款时间
     */
    private LocalDateTime subsidyRefundTime;

    /**
     * 补贴退款金额
     */
    private BigDecimal subsidyRefundAmount;

    /**
     * 用户等级（享受补贴时的用户等级）
     */
    private String userLevel;

    /**
     * 补贴来源（1-活动补贴，2-平台补贴，3-商家补贴）
     */
    private Integer subsidySource;

    // 业务方法

    /**
     * 检查补贴是否待生效
     */
    public boolean isPendingSubsidy() {
        return Objects.equals(this.subsidyStatus, 0);
    }

    /**
     * 检查补贴是否已生效
     */
    public boolean isSubsidyEffective() {
        return Objects.equals(this.subsidyStatus, 1);
    }

    /**
     * 检查补贴是否已取消
     */
    public boolean isSubsidyCancelled() {
        return Objects.equals(this.subsidyStatus, 2);
    }

    /**
     * 检查补贴是否已退款
     */
    public boolean isSubsidyRefunded() {
        return Objects.equals(this.subsidyStatus, 3);
    }

    /**
     * 生效补贴
     */
    public void effectiveSubsidy() {
        if (isPendingSubsidy()) {
            this.subsidyStatus = 1;
            this.subsidyEffectiveTime = LocalDateTime.now();
        }
    }

    /**
     * 取消补贴
     */
    public void cancelSubsidy(String reason) {
        if (isPendingSubsidy() || isSubsidyEffective()) {
            this.subsidyStatus = 2;
            this.subsidyCancelTime = LocalDateTime.now();
            this.subsidyCancelReason = reason;
        }
    }

    /**
     * 退款补贴
     */
    public void refundSubsidy(BigDecimal refundAmount) {
        if (isSubsidyEffective()) {
            this.subsidyStatus = 3;
            this.subsidyRefundTime = LocalDateTime.now();
            this.subsidyRefundAmount = refundAmount;
        }
    }

    /**
     * 计算总补贴金额
     */
    public BigDecimal calculateTotalSubsidyAmount() {
        if (unitSubsidyAmount != null && quantity != null) {
            return unitSubsidyAmount.multiply(new BigDecimal(quantity));
        }
        return totalSubsidyAmount != null ? totalSubsidyAmount : BigDecimal.ZERO;
    }

    /**
     * 计算节省金额
     */
    public BigDecimal getSavedAmount() {
        if (originalTotalAmount != null && subsidyTotalAmount != null) {
            return originalTotalAmount.subtract(subsidyTotalAmount);
        }
        return calculateTotalSubsidyAmount();
    }

    /**
     * 计算折扣率
     */
    public BigDecimal getDiscountRate() {
        if (originalTotalAmount == null || originalTotalAmount.compareTo(BigDecimal.ZERO) <= 0 ||
            subsidyTotalAmount == null || subsidyTotalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        
        return originalTotalAmount.subtract(subsidyTotalAmount)
                                 .divide(originalTotalAmount, 2, java.math.RoundingMode.HALF_UP);
    }

    /**
     * 检查是否活动补贴
     */
    public boolean isActivitySubsidy() {
        return Objects.equals(this.subsidySource, 1);
    }

    /**
     * 检查是否平台补贴
     */
    public boolean isPlatformSubsidy() {
        return Objects.equals(this.subsidySource, 2);
    }

    /**
     * 检查是否商家补贴
     */
    public boolean isMerchantSubsidy() {
        return Objects.equals(this.subsidySource, 3);
    }

    /**
     * 获取补贴状态名称
     */
    public String getSubsidyStatusName() {
        if (subsidyStatus == null) return "未知";
        
        switch (subsidyStatus) {
            case 0: return "待生效";
            case 1: return "已生效";
            case 2: return "已取消";
            case 3: return "已退款";
            default: return "未知";
        }
    }

    /**
     * 获取补贴来源名称
     */
    public String getSubsidySourceName() {
        if (subsidySource == null) return "未知";
        
        switch (subsidySource) {
            case 1: return "活动补贴";
            case 2: return "平台补贴";
            case 3: return "商家补贴";
            default: return "未知";
        }
    }

    /**
     * 检查补贴是否可以取消
     */
    public boolean canCancelSubsidy() {
        return isPendingSubsidy() || isSubsidyEffective();
    }

    /**
     * 检查补贴是否可以退款
     */
    public boolean canRefundSubsidy() {
        return isSubsidyEffective();
    }

    /**
     * 获取可退款金额
     */
    public BigDecimal getRefundableAmount() {
        if (!canRefundSubsidy()) {
            return BigDecimal.ZERO;
        }
        
        BigDecimal total = calculateTotalSubsidyAmount();
        BigDecimal refunded = subsidyRefundAmount != null ? subsidyRefundAmount : BigDecimal.ZERO;
        
        return total.subtract(refunded).max(BigDecimal.ZERO);
    }

    /**
     * 验证补贴订单数据完整性
     */
    public boolean isValid() {
        return orderId != null && !orderId.trim().isEmpty() &&
               userId != null && !userId.trim().isEmpty() &&
               activityId != null && !activityId.trim().isEmpty() &&
               subsidyProductId != null && !subsidyProductId.trim().isEmpty() &&
               productId != null && !productId.trim().isEmpty() &&
               quantity != null && quantity > 0 &&
               originalPrice != null && originalPrice.compareTo(BigDecimal.ZERO) > 0 &&
               subsidyPrice != null && subsidyPrice.compareTo(BigDecimal.ZERO) > 0 &&
               subsidyPrice.compareTo(originalPrice) <= 0 &&
               subsidyStatus != null && subsidyStatus >= 0 && subsidyStatus <= 3 &&
               subsidySource != null && subsidySource >= 1 && subsidySource <= 3;
    }

    /**
     * 检查金额是否一致
     */
    public boolean isAmountConsistent() {
        // 检查单品金额一致性
        if (originalPrice != null && subsidyPrice != null && unitSubsidyAmount != null) {
            BigDecimal calculated = originalPrice.subtract(subsidyPrice);
            if (calculated.compareTo(unitSubsidyAmount) != 0) {
                return false;
            }
        }
        
        // 检查总金额一致性
        if (quantity != null && unitSubsidyAmount != null && totalSubsidyAmount != null) {
            BigDecimal calculated = unitSubsidyAmount.multiply(new BigDecimal(quantity));
            if (calculated.compareTo(totalSubsidyAmount) != 0) {
                return false;
            }
        }
        
        return true;
    }
}
